import 'dart:io';

import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/pages/mixin/account_security_mixin.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../../../l10n/local.dart';
import '../../../../models/account_model_3rd.dart';
import 'state.dart';

// 绑定第三方账号控制器
class Bind3rdAccountController extends GetxController
    with AccountSecurityMixin {
  // 状态
  final Bind3rdAccountState state = Bind3rdAccountState();

  @override
  void onInit() {
    super.onInit();
    // 初始化状态
    _reloadData();

    // 获取第三方账号绑定列表
    Future.delayed(const Duration(milliseconds: 300), () {
      _get3rdAuthBindingList();
    });
  }

  _reloadData() {
    if (Platform.isIOS) {
      state.accountList.value = [
        AccountModel3rd.fromJson({})..socialType = Auth3rdType.apple
      ];
    } else if (Platform.isAndroid) {
      state.accountList.value = [
        AccountModel3rd.fromJson({})..socialType = Auth3rdType.google
      ];
    }
  }

  // 第三方账号绑定列表
  _get3rdAuthBindingList() async {
    Loading.showLoading(null);
    ApiHelper().get3rdAuthBindingList().then((list) {
      Loading.dismiss();
      // 根据name更新绑定状态
      for (var account in state.accountList) {
        for (var fetchedAccount in list) {
          if (account.name == fetchedAccount.name) {
            account.bindStatus = fetchedAccount.bindStatus;
            break;
          }
        }
      }
    }).catchErrorHandler();
  }

  // 绑定第三方账号
  bind3rdAccount(bool isUnbindStatus, Auth3rdType socialType) {
    if (isUnbindStatus) {
      // 绑定
      accountSecurity3rdLogin(socialType, onSuccess: (auth3rdModel) {
        if (auth3rdModel.token == null) {
          Loading.showError(local.bind_failed);
          return;
        }
        Loading.showLoading(null);
        ApiHelper()
            .bind3rdAuthAccount(auth3rdModel.token!, socialType.name)
            .then((responseModel) {
          Loading.showSuccess(local.bind_success);
        }).catchErrorHandler();
      }, onError: () {});
    } else {
      Loading.showLoading(null);
      ApiHelper().unbind3rdAuthAccount(socialType.name).then((responseModel) {
        Loading.showSuccess(local.unbind_success);
      }).catchErrorHandler();
    }
  }
}
